package com.nwpu.am.controller.admin;

import com.nwpu.am.constant.ErrorConstant;
import com.nwpu.am.pojo.dto.PurchaseItemDTO;
import com.nwpu.am.pojo.dto.UserAddDTO;
import com.nwpu.am.pojo.entity.Part;
import com.nwpu.am.pojo.entity.PurchaseItem;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.result.Result;
import com.nwpu.am.service.PartService;
import com.nwpu.am.service.PurchaseItemService;
import com.nwpu.am.service.SupplierService;
import com.nwpu.am.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Map;

/**
 * AdminController
 *
 * @author Roy
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@RestController
@RequestMapping("/admin")
@Slf4j
@Api(tags = "管理员接口")
public class AdminController {

    @Resource
    private UserService userService;

    @Resource
    private PartService partService;

    @Resource
    private SupplierService supplierService;
    @Resource
    private PurchaseItemService purchaseItemService;


    @PostMapping("/add")
    @ApiOperation("添加用户")
    public Result<String> add(@RequestBody @Validated UserAddDTO userAddDTO) {
        // 验证用户名
        User user = userService.findByUsername(userAddDTO.getUsername());
        if (user == null) {
            userService.addUser(userAddDTO);
        } else {
            return Result.error(ErrorConstant.USER_HAS_EXISTED);
        }
        return Result.success();
    }

    @PostMapping("/submitPurchase")
    @ApiOperation("提交采购订单")
    public Result<PurchaseItem> submitPurchase(@RequestBody @Validated PurchaseItemDTO purchaseItemDTO) {
        if(userService.findByUsername(purchaseItemDTO.getUserName()) == null){
            return Result.error(ErrorConstant.USER_NOT_FIND);
        }
        if(supplierService.findSupplierByName(purchaseItemDTO.getSupplierName()) == null){
            return Result.error(ErrorConstant.SUPPLIER_NOT_FIND);
        }
        Map<String,Integer> parts = purchaseItemDTO.getParts();
        for (Map.Entry<String, Integer> entry : parts.entrySet()) {
            String partName = entry.getKey();
            ArrayList<Part> partList = partService.findPartByName(partName);
            if(partList.isEmpty()){
                return Result.error(ErrorConstant.PART_NOT_FIND);
            }
        }

        PurchaseItem purchaseItem = purchaseItemService.submitPurchase(purchaseItemDTO);

        return Result.success(purchaseItem);
    }
}
